from OWRpy import *
import redRi18n
_ = redRi18n.get_(package = 'base')

import signals 
import redRGUI 

class ecoPCA(OWRpy): 
    globalSettingsList = ['commit']
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        
        # R code for generating biplots and eigenvalues plots
        self.R('source(\''+unicode(os.path.join(redREnviron.directoryNames['libraryDir'], 'ecology', 'widgets', 'evPlot.R')).replace('\\', '//')+'\')') # broken stick model
        self.R('source(\''+unicode(os.path.join(redREnviron.directoryNames['libraryDir'], 'ecology', 'widgets', 'ecoPCA.R')).replace('\\', '//')+'\')') # eigenvalues and wrapper evPlot
        self.R('source(\''+unicode(os.path.join(redREnviron.directoryNames['libraryDir'], 'ecology', 'widgets', 'cleanplot.pca.R')).replace('\\', '//')+'\')') #  plots not rendered well in redRPlot
        
        # Python variables
        self.data = {}
        self.RFunctionParam_object = ''
        
        #Unique R variable
        self.setRvariableNames(['greenpca'])
        
        #Inputs
        self.inputs.addInput('id0', 'Data table', signals.base.RDataFrame, self.processobject) 

        #Outputs
        self.outputs.addOutput("PCA results","PCA results", signals.base.RList) #
        
        #GUI
        self.RFunctionParam_scale = redRGUI.base.radioButtons(self.controlArea,  label = "Scale", buttons = [('FALSE', 'Covariance'),('TRUE','Correlation')],
        setChecked='FALSE',orientation='horizontal')
        self.RFunctionParam_GUI_tabs = redRGUI.base.tabWidget(self.controlArea)
        self.RFunctionParam_GUI_tabsBiplot = self.RFunctionParam_GUI_tabs.createTabPage(name = "Biplot",orientation='vertical')
        self.RFunctionParam_GUI_tabsEigen = self.RFunctionParam_GUI_tabs.createTabPage(name = "Eigenvalues",orientation='vertical')
        
        #self.RFunctionParam_scaling = redRGUI.base.radioButtons(self.RFunctionParam_GUI_tabsBiplot,  label = "Scaling", buttons = [('1', 'Optimal display of objects'),('2','optimal display of variables')],
        #setChecked='1',orientation='horizontal')
        self.plotAreaBiplot = redRGUI.plotting.redRPlot(self.RFunctionParam_GUI_tabsBiplot, label = "Biplot", displayLabel = False)
        self.plotAreaBiplot.resizeCheck.uncheckAll()
        self.plotAreaBiplot.topArea.hide() # hide the graphic options bar
        self.plotAreaEigen = redRGUI.plotting.redRPlot(self.RFunctionParam_GUI_tabsEigen, label = "Eigenvalues", displayLabel = False)
        self.plotAreaEigen.topArea.hide() # hide the graphic options bar
        
        #Plot area
        #self.plotAreaFinal.optionWidgets['imageType'].setCurrentId('png')
        
        
        
        #Commit
        self.commit = redRGUI.base.commitButton(self.bottomAreaRight, _("Commit"), alignment=Qt.AlignLeft, 
        callback = self.commitFunction, processOnInput=True)
        
        
    def processobject(self, data):
        if not self.require_librarys(["vegan"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_object=data.getData()
            self.data = data
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.RFunctionParam_clust=''
            
            
    def commitFunction(self):
        if unicode(self.RFunctionParam_object) == '':
            self.status.setText('No data.')
            return

        self.R(self.Rvariables['greenpca']+'<-rda('+unicode(self.RFunctionParam_object)+', scale='+unicode(self.RFunctionParam_scale.getCheckedId())+')')
        #self.R('spscores<-scores('+unicode(self.RFunctionParam_object)+', display="sp", scaling='+unicode(self.RFunctionParam_scaling.getCheckedId())+')')
        

        self.plotAreaBiplot.plotMultiple(query = self.Rvariables['greenpca']+', point=FALSE', function = 'cleanplot.pca')
        #self.plotAreaBiplot.plotMultiple(query = self.Rvariables['greenpca']+', scaling='+unicode(self.RFunctionParam_scaling.getCheckedId()),
        #function = 'biplot.rda', layers=['text(rownames(spscores), x=spscores[,1], y=spscores[,2])'])
        self.plotAreaEigen.plotMultiple(query = 'x='+self.Rvariables['greenpca'], function = 'evplotWrapper')
        
        newPCA = signals.base.RList(self, data = self.Rvariables['greenpca'], checkVal = False)
        self.rSend("PCA results", newPCA)